package com.example.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.modal.User;
import com.example.qcweb.MyGlobal;


public class UserService {
    private static DBOpenHelper dbHelper;


    public UserService(Context context) {
        dbHelper = new DBOpenHelper(context);
    }

    //登录用
    public boolean login(String username, String password) {
        SQLiteDatabase sdb = dbHelper.getReadableDatabase();
        String sql = "select * from user where username=? and password=?";
        Cursor cursor = sdb.rawQuery(sql, new String[]{username, password});
        if (cursor.moveToFirst() == true) {
            User user = new User();
            user.setType(cursor.getString(1));
            user.setCard_id(cursor.getString(2));
            user.setUsername(cursor.getString(3));
            user.setPassword(cursor.getString(4));
            user.setRealname(cursor.getString(5));
            MyGlobal.user = user;
            cursor.close();
            return true;
        }
        return false;
    }

    //注册用
    public boolean register(User user) {
        SQLiteDatabase sdb = dbHelper.getReadableDatabase();
        String sql = "insert into user(username,password,depart,realname) values(?,?,?,?)";
        Object obj[] = {user.getUsername(), user.getPassword(), user.getRealname()};
        sdb.execSQL(sql, obj);
        return true;
    }

    //返回用户Type
    public static int findUserType(String username, String password) {
        int userType = 0;
        SQLiteDatabase sdb = dbHelper.getReadableDatabase();
        String sql = "select * from user where username=? and password=?";
        Cursor cursor = sdb.rawQuery(sql, new String[]{username, password});
        if (cursor.moveToFirst() == true) {
            userType = Integer.parseInt(cursor.getString(1));
            cursor.close();
        }
        return userType;
    }

    //返回用户真实姓名
    public static String getUserRealName(String username, String password) {

        String userrealname = "";
        SQLiteDatabase sdb = dbHelper.getReadableDatabase();
        String sql = "select * from user where username=? and password=?";
        Cursor cursor = sdb.rawQuery(sql, new String[]{username, password});
        if (cursor.moveToFirst() == true) {
            userrealname = cursor.getString(5);
            cursor.close();
        }
        return userrealname;
    }


}
